/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/lowest-common-ancestor-iii
   @Language: C++
   @Datetime: 19-04-08 12:58
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
	bool lca(TreeNode *root, TreeNode *node, deque<TreeNode*> &q){
		q.push_back(root);
		if(root==NULL) return false;
		if(root==node) return true;
		if(lca(root->left,node,q)) return true;
		q.pop_back();
		if(lca(root->right,node,q)) return true;
		q.pop_back();
		return false;
	}
public:
	/*
	 * @param root: The root of the binary tree.
	 * @param A: A TreeNode
	 * @param B: A TreeNode
	 * @return: Return the LCA of the two nodes.
	 */
	TreeNode * lowestCommonAncestor3(TreeNode * root, TreeNode * A, TreeNode * B) {
		// write your code here
		deque<TreeNode*> qa, qb;
		if(!lca(root,A,qa)) return NULL;
		if(!lca(root,B,qb)) return NULL;
		for(; qa.size() && qb.size() && qa.front()==qb.front(); qa.pop_front(),qb.pop_front())
			if(qa.front()) root=qa.front();
		return root;
	}
};
